package com.baomidou.springwind.controller.supply;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.controller.BaseController;
import com.baomidou.springwind.controller.NodeData;
import com.baomidou.springwind.entity.NetworkDelivery;
import com.baomidou.springwind.entity.NetworkPlanning;
import com.baomidou.springwind.entity.NetworkSupply;
import com.baomidou.springwind.entity.Project;
import com.baomidou.springwind.mapper.NetworkDeliveryDao;
import com.baomidou.springwind.pojo.SiteCoverBuilder;
import com.baomidou.springwind.pojo.SiteSelection;
import com.baomidou.springwind.pojo.SiteSelectionBuilder;
import com.baomidou.springwind.pojo.SiteSelectionBuilderTwo;
import com.baomidou.springwind.service.NetworkSupplyService;
import com.baomidou.springwind.service.ProjectService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.springwind.mapper.NetworkSupplyDao;
import com.baomidou.springwind.mapper.NetworkPlanningDao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 物流供应链
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/network/supply")
public class AlgorithmController extends BaseController {

    @Autowired
    private NetworkSupplyService networkSupplyService;

    @Autowired
    private NetworkSupplyDao networkSupplyDao;

    @Autowired
    private NetworkDeliveryDao networkDeliveryDao;

    @Autowired
    private NetworkPlanningDao networkPlanningDao;

    @Autowired
    private ProjectService projectService;
    /**
     * 客户分析主界面
     */
    @RequestMapping("/algorithm")
    @Permission("1001")
    public String algorithm(Model model) {
        EntityWrapper<Project> wrapper = new EntityWrapper<Project>();
        wrapper.eq("operator_id",getCurrentUserId());
        wrapper.in("state", Arrays.asList("1", "2"));
        model.addAttribute("prjList", projectService.selectList(wrapper));
        return pjaxPath("/lpp/network/supply/algorithm/main",model);
    }
    //第二个算法的结果
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar1")
    public String getMapbar1() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            }if(delivery.getType()==2){
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();
        SiteCoverBuilder builder1=new SiteCoverBuilder(siteSelectionList,secondDeliveryList);
        Map<SiteSelection, List<SiteSelection>> map=builder1.build();
        String startnode=null;
        Random random = new Random(47);
        for (Map.Entry<SiteSelection,List<SiteSelection>> entry:map.entrySet()){
                        JSONArray nodes = new JSONArray();
                        JSONArray res = new JSONArray();
                        JSONObject serie=new JSONObject();
                        startnode=entry.getKey().getName();
                        for(int j=0;j<entry.getValue().size();j++){
                          nodes.add(new NodeData(startnode, Arrays.asList(entry.getValue().get(j).getCoordinateX(),entry.getValue().get(j).getCoordinateY(), random.nextInt(100))));
                           JSONObject res1 = parseRes(entry,j);
                           res.add(res1);
                        }
                        serie.put("name",startnode);
                        serie.put("res", res);
                        serie.put("nodes", nodes);
                        data.add(serie);
        }
        return callbackSuccess(data);
    }

    //对res进行处理
    private JSONObject parseRes(Map.Entry<SiteSelection,List<SiteSelection>> entry,int j) {
        JSONObject res = new JSONObject();
        res.put("fromName",entry.getKey().getName());
        res.put("toName", entry.getValue().get(j).getName());
        JSONArray fromCoord = new JSONArray();
        fromCoord.add(entry.getKey().getCoordinateX());
        fromCoord.add(entry.getKey().getCoordinateY());
        JSONArray toCoord = new JSONArray();
        toCoord.add(entry.getValue().get(j).getCoordinateX());
        toCoord.add(entry.getValue().get(j).getCoordinateY());
        JSONArray coords = new JSONArray();
        coords.add(fromCoord);
        coords.add(toCoord);
        res.put("coords", coords);
        return res;
    }
    //第一个算法的结果
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar2")
    public String getMapbar2() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            }if(delivery.getType()==2) {
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();
        String startnode=null;
        Random random = new Random(47);
        for (int i=0;i<siteSelectionList.size();i++){
            JSONArray nodes = new JSONArray();
            JSONArray res = new JSONArray();
            JSONObject serie=new JSONObject();
            startnode=siteSelectionList.get(i).getName();
            for(int j=0;j<siteSelectionList.get(i).getChildren().size();j++){
                nodes.add(new NodeData(startnode, Arrays.asList(siteSelectionList.get(i).getCoordinateX(),siteSelectionList.get(i).getCoordinateY(), random.nextInt(100))));
                JSONObject res1 = parseRes2(siteSelectionList.get(i),j);
                res.add(res1);
            }
            serie.put("name",startnode);
            serie.put("res", res);
            serie.put("nodes", nodes);
            data.add(serie);
        }
        return callbackSuccess(data);
    }
    //对res进行处理
    private JSONObject parseRes2(SiteSelection siteSelection,int j) {
        JSONObject res = new JSONObject();
        res.put("fromName",siteSelection.getName());
        res.put("toName", siteSelection.getChildren().get(j).getName());
        //开始地方
        JSONArray fromCoord = new JSONArray();
        fromCoord.add(siteSelection.getCoordinateX());
        fromCoord.add(siteSelection.getCoordinateY());
        //到达地方
        JSONArray toCoord = new JSONArray();
        toCoord.add(siteSelection.getChildren().get(j).getCoordinateX());
        toCoord.add(siteSelection.getChildren().get(j).getCoordinateY());
        JSONArray coords = new JSONArray();
        coords.add(fromCoord);
        coords.add(toCoord);
        res.put("coords", coords);
        return res;
    }
    //目前仓库的位置
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar3")
    public String getMapbar3() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
      //  wrapper.in("type", Arrays.asList(1,2));
        wrapper.eq("type", 1);
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        if(networkDeliveries.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        List<SiteSelection> siteSelectionList = new ArrayList<SiteSelection>();
        for (int i=0;i<networkDeliveries.size();i++){
            SiteSelection siteSelection=new SiteSelection();
            siteSelection.setName(networkDeliveries.get(i).getName());
            siteSelection.setOrder(networkDeliveries.get(i).getOrderQuantity());
            siteSelection.setCoordinateX(networkDeliveries.get(i).getCoordinateX());
            siteSelection.setCoordinateY(networkDeliveries.get(i).getCoordinateY());
            EntityWrapper<NetworkDelivery> wrapper1 = new EntityWrapper<NetworkDelivery>();
            wrapper1.eq("batch_id", getProjectId());
            wrapper1.eq("pid",networkDeliveries.get(i).getId());
            List<NetworkDelivery> networkDeliveries1 = networkDeliveryDao.selectList(wrapper1);
            List<SiteSelection> siteSelectionLists=new ArrayList<SiteSelection>();
            for (int j=0;j<networkDeliveries1.size();j++){
                SiteSelection siteSelection1=new SiteSelection();
                siteSelection1.setName(networkDeliveries1.get(j).getName());
                siteSelection1.setOrder(networkDeliveries1.get(j).getOrderQuantity());
                siteSelection1.setCoordinateX(networkDeliveries1.get(j).getCoordinateX());
                siteSelection1.setCoordinateY(networkDeliveries1.get(j).getCoordinateY());
                siteSelectionLists.add(siteSelection1);
            }
            siteSelection.setChildren(siteSelectionLists);
            siteSelectionList.add(siteSelection);
        }

        String startnode=null;
        Random random = new Random(47);
        for (int i=0;i<siteSelectionList.size();i++){
            JSONArray nodes = new JSONArray();
            JSONArray res = new JSONArray();
            JSONObject serie=new JSONObject();
            startnode=siteSelectionList.get(i).getName();
            for(int j=0;j<siteSelectionList.get(i).getChildren().size();j++){
                nodes.add(new NodeData(siteSelectionList.get(i).getChildren().get(j).getName(), Arrays.asList(siteSelectionList.get(i).getChildren().get(j).getCoordinateX(),siteSelectionList.get(i).getChildren().get(j).getCoordinateY(), random.nextInt(100))));
                JSONObject res1 = parseRes2(siteSelectionList.get(i),j);
                res.add(res1);
            }
            serie.put("name",startnode);
            serie.put("res", res);
            serie.put("nodes", nodes);
            data.add(serie);
        }
        return callbackSuccess(data);
    }

    //根据售达方，获取到二级算二级配送中心的第一算法
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar4")
    public String getMapbar4() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 2) {
                firstDeliveryList.add(delivery);
            } if(delivery.getType()==3){
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();

        String startnode=null;
        Random random = new Random(47);
        for (int i=0;i<siteSelectionList.size();i++){
            JSONArray nodes = new JSONArray();
            JSONArray res = new JSONArray();
            JSONObject serie=new JSONObject();
            startnode=siteSelectionList.get(i).getName();
            for(int j=0;j<siteSelectionList.get(i).getChildren().size();j++){
                nodes.add(new NodeData(startnode, Arrays.asList(siteSelectionList.get(i).getCoordinateX(),siteSelectionList.get(i).getCoordinateY(), random.nextInt(100))));
                JSONObject res1 = parseRes2(siteSelectionList.get(i),j);
                res.add(res1);
            }
            serie.put("name",startnode);
            serie.put("res", res);
            serie.put("nodes", nodes);
            data.add(serie);
        }
        return callbackSuccess(data);
    }

    //第二个算法的结果
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar5")
    public String getMapbar5() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkPlanning> wrapper = new EntityWrapper<NetworkPlanning>();
        wrapper.eq("batch_id",getProjectId());
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkPlanning> networkPlanningList = networkPlanningDao.selectList(wrapper);
        if(networkPlanningList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        List<NetworkDelivery> networkDeliveries=new ArrayList<NetworkDelivery>();
        for (int i=0;i<networkPlanningList.size();i++){
            NetworkDelivery networkDelivery=new NetworkDelivery();
            networkDelivery.setId(networkPlanningList.get(i).getId());
            networkDelivery.setpId(networkPlanningList.get(i).getpId());
            networkDelivery.setName(networkPlanningList.get(i).getName());
            networkDelivery.setCoordinateX(networkPlanningList.get(i).getCoordinateX());
            networkDelivery.setCoordinateY(networkPlanningList.get(i).getCoordinateY());
            networkDelivery.setOrderQuantity(networkPlanningList.get(i).getOrderQuantity());
            networkDelivery.setType(networkPlanningList.get(i).getType());
            networkDeliveries.add(networkDelivery);
        }
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            }if(delivery.getType()==2){
                secondDeliveryList.add(delivery);
            }
        }
        List<SiteSelection> siteSelectionList = new ArrayList<SiteSelection>();
        for (NetworkDelivery networkDelivery:firstDeliveryList){
            SiteSelection siteSelection=new SiteSelection();
            siteSelection.setName(networkDelivery.getName());
            siteSelection.setOrder(networkDelivery.getOrderQuantity());
            siteSelection.setCoordinateX(networkDelivery.getCoordinateX());
            siteSelection.setCoordinateY(networkDelivery.getCoordinateY());
            siteSelectionList.add(siteSelection);
        }
        SiteCoverBuilder builder1=new SiteCoverBuilder(siteSelectionList,secondDeliveryList);
        Map<SiteSelection, List<SiteSelection>> map=builder1.build();
        String startnode=null;
        Random random = new Random(47);
        for (Map.Entry<SiteSelection,List<SiteSelection>> entry:map.entrySet()){
            JSONArray nodes = new JSONArray();
            JSONArray res = new JSONArray();
            JSONObject serie=new JSONObject();
            startnode=entry.getKey().getName();
            for(int j=0;j<entry.getValue().size();j++){
                nodes.add(new NodeData(startnode, Arrays.asList(entry.getValue().get(j).getCoordinateX(),entry.getValue().get(j).getCoordinateY(), random.nextInt(100))));
                JSONObject res1 = parseRes(entry,j);
                res.add(res1);
            }
            serie.put("name",startnode);
            serie.put("res", res);
            serie.put("nodes", nodes);
            data.add(serie);
        }
        return callbackSuccess(data);
    }

    //目前仓库的位置
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar6")
    public String getMapbar6() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.in("type", Arrays.asList(1));
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        if(networkDeliveries.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        String startnode=null;
        Random random = new Random(100);
        for (int i=0;i<networkDeliveries.size();i++){
            JSONArray nodes = new JSONArray();
            JSONArray res = new JSONArray();
            JSONObject serie=new JSONObject();
            startnode=networkDeliveries.get(i).getName();
            for(int j=0;j<1;j++){
                nodes.add(new NodeData(networkDeliveries.get(i).getName(), Arrays.asList(networkDeliveries.get(i).getCoordinateX(),networkDeliveries.get(i).getCoordinateY(), networkDeliveries.get(i).getOrderQuantity().divide(BigDecimal.valueOf(1000)))));
                SiteSelection siteSelection=new SiteSelection();
                siteSelection.setName(networkDeliveries.get(i).getName());
                siteSelection.setCoordinateX(networkDeliveries.get(i).getCoordinateX());
                siteSelection.setCoordinateY(networkDeliveries.get(i).getCoordinateY());
                JSONObject res1 = parseRes3(siteSelection);
                res.add(res1);
            }
            serie.put("name",startnode);
            serie.put("res", res);
            serie.put("nodes", nodes);
            data.add(serie);
        }
        if (data.size()==0){
            return callbackFail("");
        }
        return callbackSuccess(data);
    }
    //对res进行处理
    private JSONObject parseRes3(SiteSelection siteSelection) {
        JSONObject res = new JSONObject();
        res.put("fromName",siteSelection.getName());
        res.put("toName", "");
        //开始地方
        JSONArray fromCoord = new JSONArray();
        fromCoord.add(siteSelection.getCoordinateX());
        fromCoord.add(siteSelection.getCoordinateY());
        //到达地方
        JSONArray toCoord = new JSONArray();
        toCoord.add("");
        toCoord.add("");
        JSONArray coords = new JSONArray();
        coords.add(fromCoord);
        coords.add(toCoord);
        res.put("coords", coords);
        return res;
    }
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/algorithm/bar7")
    public byte[] expend() {
        JSONArray data = new JSONArray();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("operator_id", getCurrentUserId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            }if(delivery.getType()==2){
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();
        SiteCoverBuilder builder1=new SiteCoverBuilder(siteSelectionList,secondDeliveryList);
        Map<SiteSelection, List<SiteSelection>> map=builder1.build();
        try{
            HSSFWorkbook wb=new HSSFWorkbook();
            HSSFSheet sheet=wb.createSheet("sheet");
            HSSFRow row=sheet.createRow(0);
            HSSFCell cell1=row.createCell(0);
            cell1.setCellValue("一级配送中心");
            HSSFCell cell2=row.createCell(1);
            cell2.setCellValue("二级配送中心");
            int i=1;
            for(Map.Entry<SiteSelection,List<SiteSelection>> entry:map.entrySet()){
                for (int i1=0;i1<entry.getValue().size();i1++){
                    HSSFRow row1=sheet.createRow(i++);
                    HSSFCell cellcenter=row1.createCell(0);
                    cellcenter.setCellValue(entry.getKey().getName());
                    HSSFCell cellorders=row1.createCell(1);
                    cellorders.setCellValue(entry.getKey().getOrder().doubleValue());
                    HSSFCell celldelivery=row1.createCell(2);
                    celldelivery.setCellValue(entry.getValue().get(i1).getName());
                    HSSFCell cellorder=row1.createCell(3);
                    cellorder.setCellValue(entry.getValue().get(i1).getOrder().doubleValue());
                }

            }

            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        new String(("测试"+ ".xls").getBytes(), "iso-8859-1"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                wb.write(output); // write
            } catch (Exception e) {
                e.printStackTrace();
            }
            return output.toByteArray();
        }catch (Exception e){
            System.out.println("报错");
        }
        //return callbackSuccess(data);
        return null;
    }
    @RequestMapping("/algorithm/bar111")
    @Permission("1001")
    public String bar111(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/algorithm/bar1";
    }
    @RequestMapping("/algorithm/bar21")
    @Permission("1001")
    public String bar21(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/algorithm/bar21";
    }
    @RequestMapping("/algorithm/bar31")
    @Permission("1001")
    public String bar31(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/algorithm/bar31";
    }
    @RequestMapping("/algorithm/bar41")
    @Permission("1001")
    public String bar41(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/algorithm/bar41";
    }
    @RequestMapping("/algorithm/bar51")
    @Permission("1001")
    public String bar51(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/algorithm/bar51";
    }





}
